package thread;

/**
 * 死锁
 * 注意，尽量不要出现在持有一个锁对象的过程中去锁另一个对象
 */
public class SyncDemo6 {
    private static Object chopsticks = new Object();//筷子
    private static Object spoon = new Object();//勺
    public static void main(String[] args) {
        //北方人
        Thread np = new Thread(){
            public void run(){
                System.out.println("北方人开始用餐...");
                System.out.println("北方人去拿筷子...");
                synchronized (chopsticks) {
                    System.out.println("北方人拿起了筷子开始吃饭...");
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                    }
                    System.out.println("北方人吃完了饭");
                }
                System.out.println("北方人放下了筷子");
                System.out.println("北方人去拿勺...");
                synchronized (spoon){
                    System.out.println("北方人拿起了勺开始喝汤...");
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                    }
                    System.out.println("北方人快喝完了汤");
                }
                System.out.println("北方人放下了勺");
                System.out.println("北方人用餐完毕");
            }
        };
        //南方人
        Thread sp = new Thread(){
            public void run(){
                System.out.println("南方人开始用餐...");
                System.out.println("南方人去拿勺...");
                synchronized (spoon) {
                    System.out.println("南方人拿起了勺开始喝汤...");
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                    }
                    System.out.println("南方人喝完了汤");
                }
                System.out.println("南方人放下了勺");
                System.out.println("南方人去拿筷子...");
                synchronized (chopsticks){
                    System.out.println("南方人拿起了筷子开始吃饭...");
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                    }
                    System.out.println("南方人吃完了饭");
                }
                System.out.println("南方人放下了筷子");
                System.out.println("南方人用餐完毕");
            }
        };

        np.start();
        sp.start();
    }
}






